<?php
$yhsdk_init = true;
$bot_token = 'd32b2be697644de9b1a1c2cef455c192';
require __DIR__ . '/yh.sdk.php';

// 初始化SQLite数据库连接
$db = new PDO('sqlite:group_subscriptions.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 创建订阅表（如果不存在）
$db->exec("CREATE TABLE IF NOT EXISTS subscriptions (
    recv_id INTEGER NOT NULL,
    group_id INTEGER NOT NULL,
    UNIQUE(recv_id, group_id) ON CONFLICT IGNORE
)");

if ($back['type'] == 'group') {
    $currentGroupId = (int)$back['id'];

    if ($event_type == 'message.receive.instruction') {
        // ================= 权限校验 =================
        $needAuth = in_array($cmdId, [1426, 1427, 1431]);
        if ($needAuth && $level != 'administrator' && $level != 'owner') {
            send($back, 'text', '❌ 仅群主/管理员可执行此操作');
            return;
        }

        try {
            switch ($cmdId) {
                // ---------- 绑定来源群 [1426] ----------
                case 1426:
                    if (!is_numeric($content)) {
                        send($back, 'text', '❌ 格式错误：群ID必须为数字');
                        return;
                    }
                    $sourceGroupId = (int)$content;

                    $stmt = $db->prepare("INSERT INTO subscriptions (recv_id, group_id) VALUES (?, ?)");
                    $stmt->execute([$currentGroupId, $sourceGroupId]);
                    
                    if ($stmt->rowCount() > 0) {
                        send($back, 'text', "✅ 成功订阅群组 {$sourceGroupId} 的消息");
                    } else {
                        send($back, 'text', "⚠️ 订阅关系已存在");
                    }
                    break;

                // ---------- 解绑来源群 [1427] ----------
                case 1427:
                    if (!is_numeric($content)) {
                        send($back, 'text', '❌ 格式错误：群ID必须为数字');
                        return;
                    }
                    $sourceGroupId = (int)$content;

                    $stmt = $db->prepare("DELETE FROM subscriptions WHERE recv_id = ? AND group_id = ?");
                    $stmt->execute([$currentGroupId, $sourceGroupId]);
                    
                    if ($stmt->rowCount() > 0) {
                        send($back, 'text', "✅ 已取消订阅群组 {$sourceGroupId}");
                    } else {
                        send($back, 'text', "⚠️ 未找到相关订阅");
                    }
                    break;

                // ---------- 查看本群订阅的群 [1429] ----------
                case 1429:
                    $stmt = $db->prepare("SELECT group_id FROM subscriptions WHERE recv_id = ?");
                    $stmt->execute([$currentGroupId]);
                    $groups = $stmt->fetchAll(PDO::FETCH_COLUMN);

                    if (empty($groups)) {
                        send($back, 'text', "⚠️ 本群尚未订阅任何群组");
                    } else {
                        $list = array_map(fn($id) => "· 来源群ID：{$id}", $groups);
                        send($back, 'text', "📋 订阅的群组列表：\n".implode("\n", $list));
                    }
                    break;

                // ---------- 查看订阅本群的群 [1430] ----------
                case 1430:
                    $stmt = $db->prepare("SELECT recv_id FROM subscriptions WHERE group_id = ?");
                    $stmt->execute([$currentGroupId]);
                    $receivers = $stmt->fetchAll(PDO::FETCH_COLUMN);

                    if (empty($receivers)) {
                        send($back, 'text', "⚠️ 没有群组订阅本群");
                    } else {
                        $list = array_map(fn($id) => "· 接收群ID：{$id}（使用 /被解绑 {$id} 取消）", $receivers);
                        send($back, 'text', "📋 订阅本群的群组：\n".implode("\n", $list));
                    }
                    break;

                // ---------- 被绑定解绑 [1431] ----------
                case 1431:
                    if (!is_numeric($content)) {
                        send($back, 'text', '❌ 格式错误：请输入接收群ID');
                        return;
                    }
                    $recvGroupId = (int)$content;

                    $stmt = $db->prepare("DELETE FROM subscriptions WHERE group_id = ? AND recv_id = ?");
                    $stmt->execute([$currentGroupId, $recvGroupId]);
                    
                    if ($stmt->rowCount() > 0) {
                        send($back, 'text', "✅ 已解除群组 {$recvGroupId} 对本群的订阅");
                    } else {
                        send($back, 'text', "⚠️ 未找到群组 {$recvGroupId} 的订阅");
                    }
                    break;
            }
        } catch (PDOException $e) {
            send($back, 'text', '❌ 操作失败：数据库异常');
        }
    } 
    // ================= 消息转发逻辑 =================
    elseif ($event_type == 'message.receive.normal') {
        try {
            $sourceGroupId = (int)$back['id'];
            $stmt = $db->prepare("SELECT recv_id FROM subscriptions WHERE group_id = ?");
            $stmt->execute([$sourceGroupId]);
            $targetGroups = $stmt->fetchAll(PDO::FETCH_COLUMN);

            foreach ($targetGroups as $recvId) {
                send([
                    'type' => 'group',
                    'id' => $recvId
                ], 'text', $content);
            }
        } catch (PDOException $e) {
            error_log("[消息转发错误] ".date('Y-m-d H:i:s')." - ".$e->getMessage());
        }
    }
} else {
    send($back, 'text', '❌ 请在群聊中使用此功能');
}
?>